import { defineStore } from 'pinia'
import { userAPI, roleAPI } from '@/api'

export const useUserStore = defineStore('user', {
  state: () => ({
    users: [],
    roles: [],
    loading: false,
    total: 0,
    currentPage: 1,
    pageSize: 10
  }),
  
  actions: {
    // 获取用户列表
    async fetchUsers(params = {}) {
      this.loading = true
      try {
        const response = await userAPI.getUserList({
          page: this.currentPage,
          size: this.pageSize,
          ...params
        })
        const users = response.data || response.list || []
        
        // 为每个用户获取角色信息
        for (const user of users) {
          try {
            const rolesResponse = await userAPI.getUserRoles(user.id)
            // 将角色字符串数组转换为对象数组以适配表格显示
            user.roles = (rolesResponse.data || rolesResponse || []).map(roleName => ({
              id: roleName,
              name: roleName
            }))
          } catch (error) {
            console.error(`获取用户 ${user.id} 角色失败:`, error)
            user.roles = []
          }
        }
        
        this.users = users
        this.total = response.total || 0
      } catch (error) {
        console.error('获取用户列表失败:', error)
      } finally {
        this.loading = false
      }
    },
    
    // 创建用户
    async createUser(userData) {
      try {
        // 按照要求的格式发送数据：{ "userName": "string", "email": "string", "password": "string", "confirmPassword": "string" }
        const createData = {
          userName: userData.username,
          email: userData.email,
          password: userData.password,
          confirmPassword: userData.confirmPassword
        }
        const response = await userAPI.createUser(createData)
        await this.fetchUsers() // 重新获取用户列表
        return response
      } catch (error) {
        throw error
      }
    },
    
    // 更新用户
    async updateUser(id, userData) {
      try {
        // 按照要求的格式发送数据：{ "id": "string", "email": "string" }
        const updateData = {
          id: userData.id || id,
          email: userData.email
        }
        const response = await userAPI.updateUser(updateData)
        await this.fetchUsers() // 重新获取用户列表
        return response
      } catch (error) {
        throw error
      }
    },
    
    // 删除用户
    async deleteUser(id) {
      try {
        const response = await userAPI.deleteUser(id)
        await this.fetchUsers() // 重新获取用户列表
        return response
      } catch (error) {
        throw error
      }
    },
    
    // 获取用户角色
    async getUserRoles(userId) {
      try {
        const response = await userAPI.getUserRoles(userId)
        return response
      } catch (error) {
        throw error
      }
    },

    // 修改用户密码
    async changePassword(userId, passwordData) {
      try {
        const response = await userAPI.changePassword(userId, passwordData)
        return response
      } catch (error) {
        throw error
      }
    },
    
    // 分配角色（每个用户只能有一个角色）
    async assignUserRole(userId, roleIds) {
      try {
        // 先获取用户当前的角色
        const currentRoles = await userAPI.getUserRoles(userId)
        const currentRoleNames = currentRoles.data || currentRoles || []
        
        // 移除用户的所有现有角色
        if (currentRoleNames.length > 0) {
          const removePromises = currentRoleNames.map(roleName => {
            const removeData = {
              roleName: roleName
            }
            return userAPI.removeUserRole(userId, removeData)
          })
          await Promise.all(removePromises)
        }
        
        // 分配新角色（只取第一个角色，确保单角色）
        if (roleIds.length > 0) {
          const assignData = {
            roleId: roleIds[0],
            userId: userId
          }
          await userAPI.assignRole(assignData)
        }
        
        await this.fetchUsers() // 重新获取用户列表
        return { success: true }
      } catch (error) {
        throw error
      }
    },
    
    // 获取角色列表
    async fetchRoles() {
      try {
        const response = await roleAPI.getRoleList()
        this.roles = response.data || response.list || []
      } catch (error) {
        console.error('获取角色列表失败:', error)
      }
    },
    
    // 创建角色
    async createRole(roleData) {
      try {
        const response = await roleAPI.createRole(roleData)
        await this.fetchRoles() // 重新获取角色列表
        return response
      } catch (error) {
        throw error
      }
    },
    
    // 更新角色
    async updateRole(id, roleData) {
      try {
        const response = await roleAPI.updateRole(id, roleData)
        await this.fetchRoles() // 重新获取角色列表
        return response
      } catch (error) {
        throw error
      }
    },
    
    // 删除角色
    async deleteRole(id) {
      try {
        const response = await roleAPI.deleteRole(id)
        await this.fetchRoles() // 重新获取角色列表
        return response
      } catch (error) {
        throw error
      }
    },
    
    // 设置分页参数
    setPage(page) {
      this.currentPage = page
    },
    
    setPageSize(size) {
      this.pageSize = size
    }
  }
})